package com.Xht.www.dao;

import com.Xht.www.po.MerchantBlacklistPO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MerchantBlacklistDAO extends BaseDAO {

    // 插入商家黑名单信息
    public boolean insertMerchantBlacklist(MerchantBlacklistPO merchantBlacklistPO) {
        if (isInsertInputInvalid(merchantBlacklistPO)) {
            System.err.println("插入商家黑名单信息时，传入的 MerchantBlacklistPO 对象或其属性不符合要求");
            return false;
        }
        String sql = "INSERT INTO merchant_blacklist (merchant_name, user_id, blacklist_time, reason) VALUES (?,?,?,?)";
        try (Connection connection = getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, merchantBlacklistPO.getMerchantName());
            pstmt.setInt(2, merchantBlacklistPO.getUserId());
            pstmt.setTimestamp(3, merchantBlacklistPO.getBlacklistTime());
            pstmt.setString(4, merchantBlacklistPO.getReason());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    // 验证插入操作的输入是否无效
    private boolean isInsertInputInvalid(MerchantBlacklistPO merchantBlacklistPO) {
        return merchantBlacklistPO == null ||
                merchantBlacklistPO.getMerchantName() == null || merchantBlacklistPO.getMerchantName().trim().isEmpty() ||
                merchantBlacklistPO.getUserId() <= 0 ||
                merchantBlacklistPO.getBlacklistTime() == null ||
                merchantBlacklistPO.getReason() == null || merchantBlacklistPO.getReason().trim().isEmpty();
    }

    // 查询所有商家黑名单信息
    public List<MerchantBlacklistPO> getAllMerchantBlacklist() {
        List<MerchantBlacklistPO> blacklistList = new ArrayList<>();
        String sql = "SELECT blacklist_id, merchant_name, user_id, blacklist_time, reason FROM merchant_blacklist";
        try (Connection connection = getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                MerchantBlacklistPO blacklistPO = new MerchantBlacklistPO();
                blacklistPO.setBlacklistId(rs.getInt("blacklist_id"));
                blacklistPO.setMerchantName(rs.getString("merchant_name"));
                blacklistPO.setUserId(rs.getInt("user_id"));
                blacklistPO.setBlacklistTime(rs.getTimestamp("blacklist_time"));
                blacklistPO.setReason(rs.getString("reason"));
                blacklistList.add(blacklistPO);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return blacklistList;
    }
}
